################################################################################
# The NOTE MANAGER CLASS
#   A Graphical User Interface
#
#   Allows the user to select notes to be:
#       Deleted
#       Renamed -- May have problems here because of the paper type included in naming files.
#       Moved to other directories
#       Created
#
#
#   To Read in .PDF into a list of names: http://www.diveintopython.net/file_handling/os_module.html
#   To turn list of strings into listbox: http://effbot.org/tkinterbook/listbox.htm
#   PDF manipulation: http://pybrary.net/pyPdf/
#   Example on how to detect a button click on a listbox: http://www.daniweb.com/software-development/python/threads/65786
#   Another example : http://stackoverflow.com/questions/2931053/python-tkinter-label-bound-to-stringvar-is-one-click-behind-when-updating
################################################################################
from Tkinter import *
from NotesClass import *
from ttk import *
from tkSimpleDialog import askstring
from distutils.dir_util import copy_tree
import tkMessageBox
import glob
import os
import shutil

#To be filled in with functionalities
class NoteManagerClass( Frame ):
    def __init__(self, root, obj, path):
        self.path = path
        self.root = root
        self.obj = obj
        self.childframe = Frame(self.root)
        self.root.grid
        self.move_flag = "false"
        self.createWidgets()

    def createWidgets(self):
        self.titleLbl = Label(self.root, text="Notes Manager", font=("Lucida Handwriting", 12, 'italic'))
        self.titleLbl.grid(row=0, column=0, columnspan=10, sticky = N + W)

        self.vsb = Scrollbar(self.root)
        self.notesList = Treeview(self.root,columns=("fullpath","type"), displaycolumns="", show="tree", height=23)
        self.vsb.config(command=self.notesList.yview)
        self.notesList.config(yscrollcommand=self.vsb.set)
        self.vsb.pack(side=RIGHT, fill=Y)
        self.vsb.grid(row=1, column=10, sticky='ns')
        self.notesList.column("#0", stretch = 0, width=1000)
        self.notesList.grid(row=1, column=0, columnspan=9)
        self.notesList.bind('<<TreeviewOpen>>', self.update_tree)
        #self.notesList.bind('<Double-Button-1>', self.openNotesClass)
        self.notesList.bind('<Button-1>', self.select)

        node = self.notesList.insert('',"end","toplevel",text="Notebook",values = [self.path,"directory"], open="true")
        self.populate_tree(self.notesList,node)

        self.homePic = PhotoImage(file="icons/home.gif")
        self.open = PhotoImage(file="icons/new_page.gif")
        self.folder_add = PhotoImage(file="icons/folder_add.gif")
        self.trash_img = PhotoImage(file="icons/trash.gif")
        self.move_img = PhotoImage(file="icons/move.gif")
        self.rename_img = PhotoImage(file="icons/edit_text.gif")
        self.info_img = PhotoImage(file="icons/info.gif")
        self.menubar = Menu(self.root, background="light gray")

        self.menubar.add_command(image=self.homePic, command=self.quit)
        self.menubar.add_command(image=self.open, command=self.openNotesClass)
        self.menubar.add_command(image=self.folder_add, command=self.makeNewFolder)
        self.menubar.add_command(image=self.trash_img, command=self.deleteFile)
        self.menubar.add_command(image=self.move_img, command=self.move)
        self.menubar.add_command(image=self.rename_img, command=self.rename)
        self.menubar.add_command(image=self.info_img, command=self.info)
        self.root.config(menu=self.menubar)




    def initializeTree(self):
        # insert folder names into the list
        folders = [ name for name in os.listdir(self.path) if os.path.isdir(os.path.join(self.path, name)) ]

        self.folder_icon = PhotoImage(file="icons/folder_small.gif")

        for folderName in range(len(folders)):
            self.notesList.insert("toplevel",'end',"dir%s"%folderName,text=folders[folderName],image=self.folder_icon)

        # insert the file names
        list = glob.glob('*.gif')
        index = 0

        self.file_icon = PhotoImage(file="icons/file.gif")

        for item in list:
            for character in range(len(item)):
                if (item[character] == "\\"):
                    index = character+1
            self.notesList.insert("toplevel",'end', text=item, image=self.file_icon)

    def updateListbox(self):
        self.notesList.delete(0, END)
        self.initializeListbox()

        #print self.notesList.index(ACTIVE)
        #print self.notesList.get(ACTIVE)

    def makeNewFolder(self):
        #os.system('matchbox-keyboard&')
        name = askstring('New Folder', 'Enter the folder name:')
        if name == None:
            return
        #os.system('killall matchbox-keyboard')
        node = self.notesList.focus()
        path = self.notesList.set(node, "fullpath")
        parent = self.notesList.parent(node)

        if os.path.isfile(path):
            path = os.path.split(path)[0]
        try:
            os.mkdir("%s" % (os.path.join(path, name)))
        except OSError as e:
            tkMessageBox.showerror("Error", "File name \"%s\" already exists!" % name)



#        self.notesList.selection(selop="set", items=node)
#        self.notesList.item(node, open = "true")
        self.notesList.focus("toplevel")
        self.update_tree(self.notesList)

    def deleteFile(self):
        node = self.notesList.focus()
 #       parent = self.notesList.parent(node)
 #       fileName = self.notesList.set(node, "fullpath")

        if tkMessageBox.askokcancel("Delete File", "Are you sure you want to delete selected items?"):
            for nodes in self.notesList.selection():
                fileName = self.notesList.set(nodes, "fullpath")

                if nodes == "toplevel":
                    tkMessageBox.showerror("Error","Notebook folder cannot be deleted!")
                    return;
                else:
                    if (self.notesList.set(nodes, "type") == 'file'):
                        os.remove("%s" % (fileName))
                    else:
                        if (self.notesList.set(nodes, "type") == 'directory'):
                            if tkMessageBox.askokcancel("Delete Directory", "Deleting the directory %s will delete all the notes inside it, are you sure you want to delete?" % os.path.split(self.notesList.set(nodes, "fullpath"))[1]):
                                shutil.rmtree("%s" % fileName)

            self.notesList.focus("toplevel")
            self.update_tree(self.notesList)
        else:
            self.notesList.focus("toplevel")
            self.update_tree(self.notesList)





    def quit(self):
        self.root.destroy()

    def openNotesClass(self):
        list = []
        for nodes in self.notesList.selection():
            if (self.notesList.set(nodes, "type") == 'file'):
                fullpath = self.notesList.set(nodes,"fullpath")
                list.append(fullpath)

        self.notesWindow = Toplevel(self.root)
        self.notesWindow.geometry("1024x450+0+0")
        self.childNote = NotesClass(self.notesWindow, self, self.path)
        self.childNote.displaySetNotes(list, 1)

        self.root.withdraw()
        self.root.wait_window(self.notesWindow)
        self.root.deiconify()

    def populate_tree(self, tree, node):
        if tree.set(node, "type") != 'directory':
            return

        self.notesList.item("toplevel", open="false")
        path = tree.set(node, "fullpath")
        tree.delete(*tree.get_children(node))

        parent = tree.parent(node)

        for p in os.listdir(path):
            ptype = None
            p = os.path.join(path, p).replace('\\', '/')

            if os.path.isdir(p): ptype = "directory"
            elif os.path.isfile(p): ptype = "file"

            fname = os.path.split(p)[1]

            if (os.path.splitext(p)[1] == ".gif"):
                id = tree.insert(node, 0, text=fname, values=[p, ptype])
            if (os.path.splitext(p)[1] == "" and fname != "icons" and fname != ".svn"):
                id = tree.insert(node, "end", text=fname, values=[p, ptype])

                if ptype == 'directory':
                    if fname not in ('.', '..'):
                        tree.insert(id, 0, text="dummy")
                        tree.item(id, text=fname)
        self.notesList.item("toplevel", open="true")
        self.notesList.selection("add", "toplevel")

    def update_tree(self):
        #self.notesList = event.widget
        self.populate_tree(self.notesList, self.notesList.focus())

    def select(self,event):
        node = self.notesList.focus()

    def move(self):
        node = self.notesList.focus()

        if (node != "toplevel"):
            tkMessageBox.askokcancel("Move File", "Are you sure you want to move the selected files?")

            if self.move_flag == "false":
                tkMessageBox.askquestion("Choose Destination","Choose a destination folder and then press the move button again to transfer the files.")
                self.nodesToMove = self.notesList.selection()
                self.moveNotes.config(relief = "raised")
                self.move_flag = "true"
                self.src = self.notesList.set(node,"fullpath")
            else:

                if(self.notesList.set(node,"type") == "directory"):
                    self.move_flag = "false"
                    self.moveNotes.config(relief = "flat")
                    dst = self.notesList.set(node,"fullpath")

                    if dst.startswith(self.src) and self.notesList.set(node,"type") == "directory":
                        tkMessageBox.showerror("Error", "A directory cannot be moved into one it its subdirectories!")
                    else:
                        for nodes in self.nodesToMove:
                            if self.notesList.set(nodes,"type") == 'file':
                                shutil.move(self.notesList.set(nodes,"fullpath"),dst)
                            else:
                                if tkMessageBox.askokcancel("Transfer Folder", "Are you sure you want to transfer folder \"%s\" and all of its contents?" % os.path.split(self.notesList.set(nodes,"fullpath"))[1]):
                                    try:
                                        os.mkdir("%s/%s" % (dst,os.path.split(self.notesList.set(nodes,"fullpath"))[1]))
                                        copy_tree(self.notesList.set(nodes,"fullpath"),"%s/%s" % (dst,os.path.split(self.notesList.set(nodes,"fullpath"))[1]))
                                        shutil.rmtree(self.src)
                                    except OSError as e:
                                        tkMessageBox.showerror("Error", "File name \"%s\" already exists!" % os.path.split(self.notesList.set(nodes,"fullpath"))[1])
                        self.notesList.focus("toplevel")
                        self.update_tree(self.notesList)

                else:
                    tkMessageBox.askokcancel("Choose Destination", "Destination must be a folder!")

        else:
            tkMessageBox.showerror("Error", "\"Notebook\" cannot be moved to another directory!")

    def info(self):
        tkMessageBox.showinfo("Note Manager","Notes Manager allows you to keep track of your notes and helps keep you organized. Use the icons on the left to create new folders, edit existing notes, delete files, move files and rename them.")

    def rename(self):
        node = self.notesList.focus()
        src = self.notesList.set(node,"fullpath")

        rename_flag = "false"

        if node != "toplevel":
            name = askstring('Rename', 'Enter the new name:')

            if self.notesList.set(node,"type") == "file" and os.path.splitext(name)[1] != ".gif":
                tkMessageBox.showerror("Error", "Renaming files requires one of the following extensions: .gif")
            else:
                if tkMessageBox.askokcancel("Rename", "Are you sure you want to rename this file or folder to \"%s\"?" % name):
                    try:
                        os.renames(src,"%s/%s" % (os.path.split(src)[0],name))
                        self.notesList.focus("toplevel")
                        self.update_tree()
                    except OSError as e:
                        tkMessageBox.showerror("Error", "File name \"%s\" already exists!" % name)
                else:
                    return
        else:
            tkMessageBox.askokcancel("Error", "\"Notebook\" cannot be renamed!")
